package cn.seapon.talker.db;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import cn.seapon.talker.bean.Account;

import com.j256.ormlite.dao.Dao;

/**
 * @author 作者 E-mail:
 * @version 创建时间：2015年1月9日 上午12:09:18 类说明
 */
public class AccountDao {

	private Context context;
	private TalkerOrmliteHelper helper;
	private Dao<Account, Integer> accountDao;

	public AccountDao(Context context) {
		this.context = context;
		try {
			helper = TalkerOrmliteHelper.getHelper(context);
			accountDao = helper.getAccountsDao();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param account
	 */
	public void addAccount(Account account) {
		try {
			deleteAccount(account);
			accountDao.create(account);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void deleteAccount(Account account){
		try {
			accountDao.delete(account);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 不存在则创建
	 * @param account
	 */
	public void setDefault(Account account){
		try {
			//全部改为false
			List<Account> accounts = accountDao.queryForAll();
			for (int i = 0; i < accounts.size(); i++) {
				Account ac = accounts.get(i);
				ac.setIs_default(false);
				accountDao.update(ac);
			}
			//设置为true
			accountDao.delete(account);
			account.setIs_default(true);
			accountDao.create(account);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public Account getDefault(){
		try {
			Account account = new Account();
			account.setIs_default(true);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("is_default", true);
			List<Account> list = accountDao.queryForFieldValuesArgs(map);
			if (list.size() > 0) {
				return list.get(0);
			}else {
				list = accountDao.queryForAll();
				if (list.size() != 0) {
					Account other = new Account();
					other.setName(list.get(0).getName());
					other.setPasswd("");
					return other;
				}else {
					return null;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void update(Account account) {
		try {
			accountDao.update(account);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
